﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ext.Net;
using InformationSystem.BLL.Core.Service;
using InformationSystem.BLL.Core.Model;
using InformationSystem.Utility;
using System.Text;
using System.Xml;

namespace InformationSystem.WebSite
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            this.LoadAuthorize();
        }
        public IUserService UserService { get; set; }
        public ISystemService SystemService { get; set; }
        protected void btnLogin_Click(object sender, DirectEventArgs e)
        {
            string username = this.txtUsername.Text;
            string password = this.txtPassword.Text;
            //if Authentication ok rediect to other pages
            LoginUser user = UserService.Login(username, password);
            if (user == null)
            {
                X.Msg.Show(new MessageBoxConfig
                {
                    Buttons = MessageBox.Button.OK,
                    Icon = MessageBox.Icon.INFO,
                    Title = "信息",
                    Message = "用户名不存在或者密码错误！"
                });
            }
            else if (user.LoginDeny)
            {
                X.Msg.Show(new MessageBoxConfig
                {
                    Buttons = MessageBox.Button.OK,
                    Icon = MessageBox.Icon.INFO,
                    Title = "信息",
                    Message = "账户被禁用，请联系辅导员!"
                });
            }
            else
            {
                //保存入Session
                Session["LoginUser"] = user;
                //获取环境设置
                SysEnvironment sysenu = new SysEnvironment();
                UserService.UpdateLoginInfo(user, sysenu);

                DateTime now = DateTime.Now.Date;
                //锁住变量
                Traffic traffic = null;
                Application.Lock();
                int vist = (int)Application[Common.VisitedCount];
                Application[Common.VisitedCount] = vist + 1;
                Visited vi = (Visited)Application[Common.VisitedToday];

                if (now == vi.Today)
                {
                    vi.Count++;
                }
                else
                {
                    traffic = new Traffic();
                    traffic.Year = vi.Today.Year;
                    traffic.Month = vi.Today.Month;
                    traffic.Day = vi.Today.Day;
                    traffic.Count = vi.Count;
                    vi.Today = now;
                    vi.Count = 1;
                }
                List<LoginUser> useronlinelist = (List<LoginUser>)Application[Common.OnLine];
                LoginUser ui = useronlinelist.Find(val => val.UserID == user.UserID);
                if (ui != null)
                {
                    ui.LastRefreshTime = DateTime.Now;
                }
                else
                {
                    user.LastRefreshTime = DateTime.Now;
                    useronlinelist.Add(user);
                }
                Application.UnLock();

                if (traffic != null)
                {
                    SystemService.CreateTraffic(traffic);
                }

                switch (user.LoginUserType)
                {
                    case UserType.Admin:
                        Response.Redirect("Panel.aspx");
                        break;
                    case UserType.Assistant:
                    case UserType.Student:
                    case UserType.Parent:
                        Response.Redirect("Default.aspx");
                        break;
                }

            }
        }


        private void LoadAuthorize()
        {
            if (Application["License"] == null)
            {
                //加载授权
                //加载授权信息
                SysRegEnvironment sysreginfo = SystemService.ReadSystemInfo();
                if (sysreginfo == null) return;
                if (!MSecurity.RSAVerify(sysreginfo.RegData, sysreginfo.VerifyData))
                {
                    return;
                }
                string xmltxt = Encoding.ASCII.GetString(sysreginfo.RegData);

                xmltxt = MSecurity.Decrypt(xmltxt);
                if (xmltxt == string.Empty)
                {
                    return;
                }
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(xmltxt);
                bool isreg = doc.SelectSingleNode("/root/isreg").InnerText == "1" ? true : false;
                DateTime regtime = DateTime.Parse(doc.SelectSingleNode("/root/regtime").InnerText);
                string regid = doc.SelectSingleNode("/root/regid").InnerText;
                DateTime regendtime = DateTime.Parse(doc.SelectSingleNode("/root/end").InnerText);

                if (regid != sysreginfo.RegID)
                {
                    return;
                }
                if (regendtime < DateTime.Now)
                {
                    return;
                }
                SysEnvironment sement = new SysEnvironment();
                sement.EndTime = regendtime;
                sement.IsRegisted = isreg;
                sement.RegisterGuid = regid;
                sement.RegisterTime = regtime;
                Application.Lock();
                Application[Common.AppRegInfo] = sement;
                Application.UnLock();

                Application["License"] = 1;
            }
        }
    }
}